import axios, {
  AxiosError,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from 'axios';

import type { ApiResponse } from '@/types/global';

// 创建axios实例
const api = axios.create({
  baseURL: process.env.NEXT_PUBLIC_API_BASE_URL || 'https://api.example.com',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// Token管理
class TokenManager {
  private static readonly TOKEN_KEY = 'auth_token';

  static getToken(): string | null {
    if (typeof window === 'undefined') return null;
    return localStorage.getItem(this.TOKEN_KEY);
  }

  static setToken(token: string): void {
    if (typeof window !== 'undefined') {
      localStorage.setItem(this.TOKEN_KEY, token);
    }
  }

  static removeToken(): void {
    if (typeof window !== 'undefined') {
      localStorage.removeItem(this.TOKEN_KEY);
    }
  }
}

// 请求拦截器
api.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 添加认证token
    const token = TokenManager.getToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    // 添加语言设置
    const locale =
      typeof window !== 'undefined'
        ? localStorage.getItem('locale') || 'zh'
        : 'zh';
    config.headers['Accept-Language'] = locale;

    // 添加请求时间戳
    config.headers['X-Request-Time'] = new Date().toISOString();

    if (process.env.NODE_ENV === 'development') {
      console.log('API Request:', {
        method: config.method?.toUpperCase(),
        url: config.url,
        data: config.data,
      });
    }

    return config;
  },
  (error: AxiosError) => {
    console.error('Request Error:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse<ApiResponse>) => {
    if (process.env.NODE_ENV === 'development') {
      console.log('API Response:', {
        status: response.status,
        data: response.data,
      });
    }
    return response;
  },
  (error: AxiosError<ApiResponse>) => {
    // 处理常见的HTTP错误状态码
    if (error.response) {
      const { status, data } = error.response;

      switch (status) {
        case 401:
          // 未授权，清除token并跳转到登录页
          TokenManager.removeToken();
          if (typeof window !== 'undefined') {
            window.location.href = '/login';
          }
          break;
        case 403:
          console.error('Access denied:', data?.message);
          break;
        case 404:
          console.error('Resource not found:', data?.message);
          break;
        case 422:
          console.error('Validation error:', data);
          break;
        case 500:
          console.error('Internal server error:', data?.message);
          break;
        default:
          console.error('API Error:', data?.message || 'Unknown error');
      }
    } else if (error.request) {
      console.error('Network error:', error.message);
    } else {
      console.error('Request setup error:', error.message);
    }

    return Promise.reject(error);
  }
);

// 通用API方法
export const apiClient = {
  get: <T = unknown>(url: string, config?: object) =>
    api.get<ApiResponse<T>>(url, config),

  post: <T = unknown>(url: string, data?: unknown, config?: object) =>
    api.post<ApiResponse<T>>(url, data, config),

  put: <T = unknown>(url: string, data?: unknown, config?: object) =>
    api.put<ApiResponse<T>>(url, data, config),

  patch: <T = unknown>(url: string, data?: unknown, config?: object) =>
    api.patch<ApiResponse<T>>(url, data, config),

  delete: <T = unknown>(url: string, config?: object) =>
    api.delete<ApiResponse<T>>(url, config),
};

// 用户类型定义
export interface User {
  id: string;
  name: string;
  email: string;
  avatar?: string;
  role?: string;
  createdAt: string;
  updatedAt: string;
}

export interface LoginCredentials {
  email: string;
  password: string;
}

export interface RegisterData {
  email: string;
  password: string;
  name: string;
  confirmPassword?: string;
}

export interface LoginResponse {
  token: string;
  user: User;
  expiresIn: number;
}

export interface UpdateProfileData {
  name?: string;
  email?: string;
  avatar?: string;
}

// 用户相关API
export const userApi = {
  // 获取用户信息
  getProfile: () => apiClient.get<User>('/user/profile'),

  // 更新用户信息
  updateProfile: (data: UpdateProfileData) =>
    apiClient.put<User>('/user/profile', data),

  // 用户登录
  login: (credentials: LoginCredentials) =>
    apiClient.post<LoginResponse>('/auth/login', credentials),

  // 用户注册
  register: (data: RegisterData) =>
    apiClient.post<User>('/auth/register', data),

  // 用户登出
  logout: () => apiClient.post<{ message: string }>('/auth/logout'),

  // 刷新token
  refreshToken: () => apiClient.post<{ token: string }>('/auth/refresh'),

  // 重置密码
  resetPassword: (email: string) =>
    apiClient.post<{ message: string }>('/auth/reset-password', { email }),

  // 修改密码
  changePassword: (data: { oldPassword: string; newPassword: string }) =>
    apiClient.put<{ message: string }>('/auth/change-password', data),
};

// 企业数据API
export interface DashboardData {
  stats: {
    totalUsers: number;
    totalRevenue: number;
    totalOrders: number;
    conversionRate: number;
  };
  charts: {
    revenue: Array<{ date: string; value: number }>;
    users: Array<{ date: string; value: number }>;
  };
}

export interface AnalyticsParams {
  startDate?: string;
  endDate?: string;
  metric?: string;
}

export const enterpriseApi = {
  // 获取仪表板数据
  getDashboardData: () => apiClient.get<DashboardData>('/dashboard'),

  // 获取分析报告
  getAnalytics: (params?: AnalyticsParams) =>
    apiClient.get<Record<string, unknown>>('/analytics', { params }),

  // 获取企业统计
  getStatistics: () => apiClient.get<Record<string, unknown>>('/statistics'),
};

// 导出token管理器
export { TokenManager };
export default api;
